package com.androidbook.btdt_week9;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class QuizScoresActivity extends QuizActivity {
	int mProgressCounter = 0;
	 ScoreDownloaderTask allScoresDownloader;
	 ScoreDownloaderTask friendScoresDownloader;
	 ScoreDownloaderTask followerScoresDownloader;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.scores);
        
        // Set up the tabs
        TabHost host = (TabHost) findViewById(R.id.TabHost1);
        host.setup();
        
        // All Scores tab
        TabSpec allScoresTab = host.newTabSpec("allTab");
        allScoresTab.setIndicator(getResources().getString(R.string.all_scores), getResources().getDrawable(
                android.R.drawable.star_on));
        allScoresTab.setContent(R.id.ScrollViewAllScores);
        host.addTab(allScoresTab);
        
        // Friends Scores tab
        TabSpec friendScoresTab = host.newTabSpec("friendsTab");
        friendScoresTab.setIndicator(getResources().getString(R.string.friends_scores), getResources().getDrawable(
                android.R.drawable.star_on));
        friendScoresTab.setContent(R.id.ScrollViewFriendScores);
        host.addTab(friendScoresTab);
        
        // Followers Scores tab
        TabSpec followerScoresTab = host.newTabSpec("followersTab");
        followerScoresTab.setIndicator(getResources().getString(R.string.followers_scores), getResources().getDrawable(
                android.R.drawable.star_on));
        followerScoresTab.setContent(R.id.ScrollViewFollowersScores);
        host.addTab(followerScoresTab);
        
        // Set the default tab
        host.setCurrentTabByTag("allTab");
        
        // Retrieve the TableLayout references
        TableLayout allScoresTable = (TableLayout) findViewById(R.id.TableLayout_AllScores);
        TableLayout friendScoresTable = (TableLayout) findViewById(R.id.TableLayout_FriendScores);
        TableLayout followerScoresTable = (TableLayout) findViewById(R.id.TableLayout_FollowerScores);
        
        // Give each TableLayout a yellow header row with the column names
        initializeHeaderRow(allScoresTable);
        initializeHeaderRow(friendScoresTable);
        initializeHeaderRow(followerScoresTable);
        
        //Antiguo------------------------------------------------------------------------
//        XmlResourceParser mockAllScores = getResources().getXml(R.xml.allscores);
//        XmlResourceParser mockFriendScores = getResources().getXml(R.xml.friendscores);
//        try {
//            processScores(allScoresTable, mockAllScores);
//            processScores(friendScoresTable, mockFriendScores);
//        } catch (Exception e) {
//            Log.e(TAG, "Failed to load scores", e);
//        }
        //-------------------------------------------------------------------------------
        
        allScoresDownloader = new ScoreDownloaderTask();
        allScoresDownloader.execute(TRIVIA_SERVER_SCORES, allScoresTable);

        //Integer playerId = 2008;
        SharedPreferences prefs = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
        Integer playerId = prefs.getInt(GAME_PREFERENCES_PLAYER_ID, -1);

        if (playerId != -1) {
        	friendScoresDownloader = new ScoreDownloaderTask();
            friendScoresDownloader.execute(TRIVIA_SERVER_SCORES + "?playerId=" + playerId, 
            		friendScoresTable);
        }
        
        if (playerId != -1) {
        	followerScoresDownloader = new ScoreDownloaderTask();
        	followerScoresDownloader.execute(TRIVIA_SERVER_SCORES + "?playerId=" + playerId 
        			+ "&followers=true", followerScoresTable);
        }
        
    }
    
    @Override
    protected void onPause() {
    	if (allScoresDownloader != null && allScoresDownloader.getStatus() != 
    			AsyncTask.Status.FINISHED) {
    		allScoresDownloader.cancel(true);
    	}
    	if (friendScoresDownloader != null && friendScoresDownloader.getStatus() != 
    			AsyncTask.Status.FINISHED) {
    		friendScoresDownloader.cancel(true);
    	}
    	if (followerScoresDownloader != null && followerScoresDownloader.getStatus() != 
    			AsyncTask.Status.FINISHED) {
    		followerScoresDownloader.cancel(true);
    	}
    	super.onPause();
    }

    /**
     * Add a header {@code TableRow} to the {@code TableLayout} (styled)
     * 
     * @param scoreTable
     *            the {@code TableLayout} that the header row will be added to
     */
    private void initializeHeaderRow(TableLayout scoreTable) {
        // Create the Table header row
        TableRow headerRow = new TableRow(this);
        Resources resour = getResources();
        int textColor = resour.getColor(R.color.logo_color);
        float textSize = resour.getDimension(R.dimen.help_text_size);
        if (scoreTable.getId() == R.id.TableLayout_FriendScores ) {
        	String texto = resour.getString(R.string.avatarImage);
        	if (texto == null) {
        		
        	}
        	addTextToRowWithValues(headerRow, texto, 
            		textColor, textSize);
        }
        addTextToRowWithValues(headerRow, resour.getString(R.string.username), 
        		textColor, textSize);
        addTextToRowWithValues(headerRow, resour.getString(R.string.score), 
        		textColor, textSize);
        addTextToRowWithValues(headerRow, resour.getString(R.string.rank), 
        		textColor, textSize);
        scoreTable.addView(headerRow);
    }

    /**
     * {@code insertScoreRow()} helper method -- Populate a {@code TableRow} with
     * three columns of {@code TextView} data (styled)
     * 
     * @param tableRow
     *            The {@code TableRow} the text is being added to
     * @param text
     *            The text to add
     * @param textColor
     *            The color to make the text
     * @param textSize
     *            The size to make the text
     */
    private void addTextToRowWithValues(final TableRow tableRow, String text, int textColor, float textSize) {
        TextView textView = new TextView(this);
        textView.setTextSize(textSize);
        textView.setTextColor(textColor);
        textView.setText(text);
        textView.setLines(1);		// Para que los nicknames largos
        textView.setMaxWidth(150);	//... queden bien
        tableRow.addView(textView);
    }
    
    private void addImageToRow (final TableRow tableRow, Bitmap bm) {
    	ImageView imView = new ImageView(this);
    	imView.setImageBitmap(bm);
    	getResizedBitmap(bm, 40, 40);
    	tableRow.addView(imView);
    }
    

	private Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		
		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		
		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);
		
		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);		
		return resizedBitmap;	
	}


    
    private class ScoreDownloaderTask extends AsyncTask<Object, String, Boolean> {
    	private static final String DEBUG_TAG = "ScoreDownloaderTask";
    	TableLayout table;
    	String objeto;

    	@Override
    	protected void onCancelled() {
    		Log.i(DEBUG_TAG, ">> onCancelled + objeto");
    		mProgressCounter--;
    		if (mProgressCounter <= 0) {
    			mProgressCounter = 0;
    			QuizScoresActivity.this.setProgressBarIndeterminateVisibility(false);
    		}
    		Log.d(DEBUG_TAG, "<<>> End onCancelled + objeto");
    	}

    	@Override
    	protected void onPostExecute(Boolean result) {
    		Log.i(DEBUG_TAG, ">> onPostExecute" + objeto);
    		mProgressCounter--;
    		if (mProgressCounter <= 0) {
    			mProgressCounter = 0;
    			QuizScoresActivity.this.setProgressBarIndeterminateVisibility(false);
    		}
    		Log.d(DEBUG_TAG, "<<>> End onPostExecute" + objeto);
    	}
    	
    	@Override
    	protected void onPreExecute() {
    		Log.d(TAG, ">> onPreExecute");
    		
    		mProgressCounter++;
    		QuizScoresActivity.this.setProgressBarIndeterminateVisibility(true);
    		Log.d(DEBUG_TAG, "<<>> End onPreExecute + objeto");
    	}

    	@Override
    	protected void onProgressUpdate(String... values) {
    		Log.d(DEBUG_TAG, ">> onProgressUpdate " + objeto);
    		String scoreValue = "";
			String scoreRank = "";
			String scoreUserName = "";
    		if (values.length != 0) {
	    		scoreValue = values[0];
				scoreRank = values[1];
				scoreUserName = values[2];
    		} else {
    			Log.d(DEBUG_TAG, ">>>>>>?????????? VALUES ES 0 PARA: " + objeto);
    		}
			
			if (values.length == 3 || values.length == 4) {
	    		if (((table.getId() == R.id.TableLayout_FollowerScores || 
	    				table.getId() ==  R.id.TableLayout_AllScores)) && (values.length == 3)) {
	    			Log.i(DEBUG_TAG, "llamada a insertScoreRow: " + objeto);
	    			insertScoreRow(table, scoreValue, scoreRank, scoreUserName);
	    		} else if ((table.getId() == R.id.TableLayout_FriendScores) && (values.length == 4)){
	    			String scoreImage = values[3];
	    			Log.i(DEBUG_TAG, "Voy a llamar a insertScoreRow: " + objeto);
	    			insertScoreRow(table, scoreValue, scoreRank, scoreUserName, scoreImage);
	    		} else {
	    			Log.e(DEBUG_TAG, "no llamo a ningun insertScoreRow para " + objeto + " >>values.length=" + values.length);
	    		}
			} else {
    			final TableRow newRow = new TableRow(QuizScoresActivity.this);
    			TextView noResults = new TextView(QuizScoresActivity.this);
    			noResults.setText(getResources().getString(R.string.no_scores));
    			newRow.addView(noResults);
    			table.addView(newRow);
    		}
			Log.d(DEBUG_TAG, "<<>> End onProgressUpdate" + objeto);
    	}

    	@Override
    	protected Boolean doInBackground(Object... params) {
    		boolean result = false;
    		String pathToScores = (String) params[0];
    		table = (TableLayout) params[1];
    		
    		//-----Debug---------------------------------------------------------------------------
    		if (table != null) {
	    		if (table.getId() == R.id.TableLayout_FollowerScores) {
	    			objeto = "<follower>";
	    		} else if (table.getId() ==  R.id.TableLayout_AllScores) {
	    			objeto = "<allScores>";
	    		} else if (table.getId() == R.id.TableLayout_FriendScores) {
	    			objeto = "<friend>";
	    		} else {
	    			objeto = "<tabla desconocida>";
	    		}
    		} else {
    			objeto = "<error>";
    		}
    		//-------------------------------------------------------------------------------------
    		
    		
    		
    		Log.d(DEBUG_TAG, ">> doInBackground" + objeto);
	    	XmlPullParser scores;
	    	try {
	    		URL xmlUrl = new URL(pathToScores);
	    		Log.d(DEBUG_TAG, ">> (1)doInBackground" + objeto);
	    		scores = XmlPullParserFactory.newInstance().newPullParser();
	    		Log.d(DEBUG_TAG, ">> (2)doInBackground" + objeto);
	    		scores.setInput(xmlUrl.openStream(), null);
	    		Log.d(DEBUG_TAG, ">> (3)doInBackground" + objeto);
	    	} catch (XmlPullParserException e) {
	    		scores = null;
	    	} catch (IOException e) {
	    		scores = null;
	    	}
	
	    	if (scores != null) {
    			try {
    				Log.d(DEBUG_TAG, ">> (4)doInBackground" + objeto);
    				if (table.getId() == R.id.TableLayout_FriendScores) {
    					processScores(scores, true);
    				} else {
    					processScores(scores, false);
    				}
    				Log.d(DEBUG_TAG, ">> (5)doInBackground" + objeto);
    			} catch (XmlPullParserException e) {
    				Log.e(DEBUG_TAG, "Pull Parser failure", e);
    			} catch (IOException e) {
    				Log.e(DEBUG_TAG, "IO Exception parsing XML", e);
    			}
    		}

	    	Log.d(DEBUG_TAG, "<<>> End doInBackground" + objeto);
    		return result;
    	}
    
	    /**
	     * Churn through an XML score information and populate a {@code TableLayout}
	     * 
	     * @param scoreTable
	     *            The {@code TableLayout} to populate
	     * @param scores
	     *            A standard {@code XmlResourceParser} containing the scores
	     * @throws XmlPullParserException
	     *             Thrown on XML errors
	     * @throws IOException
	     *             Thrown on IO errors reading the XML
	     */
	    private void processScores(XmlPullParser scores, boolean isFriendTable) throws XmlPullParserException, IOException {
	        int eventType = -1;
	        boolean bFoundScores = false;
	        // Find Score records from XML
	
	        while (eventType != XmlResourceParser.END_DOCUMENT) {
	            if (eventType == XmlResourceParser.START_TAG) {
	                // Get the name of the tag (eg scores or score)
	                String strName = scores.getName();
	                if (strName.equals("score")) {
	                    bFoundScores = true;
	                    String scoreValue = scores.getAttributeValue(null, "score");
	                    String scoreRank = scores.getAttributeValue(null, "rank");
	                    String scoreUserName = scores.getAttributeValue(null, "username");
	                    Log.d(DEBUG_TAG, "<<>> processScores "  + objeto + " value:" + scoreValue + " rank:" 
	                    		+ scoreRank + " username:" + scoreUserName);

	                    if (isFriendTable) {
	                    	String scoreImage = scores.getAttributeValue(null, "avatarUrl");
	                    	if (scoreImage == null) {
	                    		Log.d(DEBUG_TAG, "NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
	                    	}
	                    	publishProgress(scoreValue, scoreRank, scoreUserName, scoreImage);
	                    } else {
	                    	publishProgress(scoreValue, scoreRank, scoreUserName);
	                    }
	                }
	            }
	            eventType = scores.next();
	        }
	        // Handle no scores available
	
	        if (bFoundScores == false) {
	        	//--ANTIGUO--------------------------------------------------------
	//            final TableRow newRow = new TableRow(this);
	//            TextView noResults = new TextView(this);
	//            noResults.setText(getResources().getString(R.string.no_scores));
	//            newRow.addView(noResults);
	//            scoreTable.addView(newRow);
	        	//-----------------------------------------------------------------
	        	publishProgress();
	        }
	    }
	
	    /**
	     * {@code processScores()} helper method -- Inserts a new score {@code
	     * TableRow} in the {@code TableLayout}
	     *
	     * @param scoreTable
	     *            The {@code TableLayout} to add the score to
	     * @param scoreValue
	     *            The value of the score
	     * @param scoreRank
	     *            The ranking of the score
	     * @param scoreUserName
	     *            The user who made the score
	     */
	    private void insertScoreRow(final TableLayout scoreTable, String scoreValue, String scoreRank, String scoreUserName) {
	        final TableRow newRow = new TableRow(QuizScoresActivity.this);
	        int textColor = getResources().getColor(R.color.title_color);
	        float textSize = getResources().getDimension(R.dimen.help_text_size);
	        addTextToRowWithValues(newRow, scoreUserName, textColor, textSize);
	        addTextToRowWithValues(newRow, scoreValue, textColor, textSize);
	        addTextToRowWithValues(newRow, scoreRank, textColor, textSize);
	        scoreTable.addView(newRow);
	    }
	    
	    /**
	     * {@code processScores()} helper method -- Inserts a new score {@code
	     * TableRow} in the {@code TableLayout}
	     * @param scoreTable The {@code TableLayout} to add the score to
	     * @param scoreValue The value of the score
	     * @param scoreRank The ranking of the score
	     * @param scoreUserName The user who made the score
	     * @param scoreImage The URI of the user image
	     */
	    private void insertScoreRow(final TableLayout scoreTable, String scoreValue, String scoreRank,
	    		String scoreUserName, String scoreImage) {
	    	
	        final TableRow newRow = new TableRow(QuizScoresActivity.this);
	        int textColor = getResources().getColor(R.color.title_color);
	        float textSize = getResources().getDimension(R.dimen.help_text_size);
	        
	        //Add image
	        URL imageUrl;
			try {
				imageUrl = new URL(scoreImage);
				InputStream stream = imageUrl.openStream();
				Bitmap bm = BitmapFactory.decodeStream(stream);
				
				addImageToRow(newRow, bm);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			addTextToRowWithValues(newRow, scoreUserName, textColor, textSize);
	        addTextToRowWithValues(newRow, scoreValue, textColor, textSize);
	        addTextToRowWithValues(newRow, scoreRank, textColor, textSize);
	        
	        scoreTable.addView(newRow);
	    }
	    

    }
    
}